package com.lcsuo.dao;

import com.dyuproject.protostuff.LinkedBuffer;
import com.dyuproject.protostuff.ProtobufIOUtil;
import com.dyuproject.protostuff.runtime.RuntimeSchema;
import com.lcsuo.bean.User;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

public class RedisDao {
	
	private JedisPool jedisPool;
	
	private RuntimeSchema<User> schema = RuntimeSchema.createFrom(User.class);
	
	/**
	 * 初始化jedisPool
	 * @param ip
	 * @param port
	 */
	public RedisDao(String ip, int port) {
		jedisPool = new JedisPool(ip, port);
	}

	/**
	 * 获取redis缓存中的值
	 * @param id
	 * @return
	 */
	public User getRedis(Integer id){
		try {
			Jedis jedis = jedisPool.getResource();
			try {
				String key = "Userkey:"+id;
				jedis.auth("123456");
				byte[] bs = jedis.get(key.getBytes());
				//自定义序列化
				if(bs != null){
					//空对象
					User user = schema.newMessage();
					ProtobufIOUtil.mergeFrom(bs, user, schema);
					//user 被反序列化
					return user;
				}
			} finally {
				jedis.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 设置redis缓存值
	 * @param user
	 * @return
	 */
	public String putRedis(User user){
		try {
			Jedis jedis = jedisPool.getResource();
			try {
				String key = "Userkey:" + user.getId();
				jedis.auth("123456");
				byte[] byteArray = ProtobufIOUtil.toByteArray(user, schema, 
						LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE));
				int seconds = 60 * 60;//设置redis缓存超时时间，一个小时
				//如果正确返回OK
				return jedis.setex(key.getBytes(), seconds, byteArray);
			} finally {
				jedis.close();
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}
